<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .box {
        position: absolute;
        top: 100px;
        left: 0;
        width: 100px;
        height: 100px;
        background-color: skyblue;
      }
    </style>
  </head>
  <body>
    <input type="button" value="开始" id="start" />
    <input type="button" value="结束" id="end" />
    <div class="box" id="box"></div>
    <script>
      var start = document.getElementById('start')
      var end = document.getElementById('end')
      var box = document.getElementById('box')
      //  偏移量
      var nowLeft = 0
      // 全局定义一个变量存储定时器
      var timer
      // 步长
      var step = 5
      start.onclick = function () {
        //每次点击先清除定时器，保证每次点击后只有一个定时器
        clearInterval(timer)
        timer = setInterval(function () {
          // 偏移量进行自加
          nowLeft += step
          if (nowLeft > 1000) {
            nowLeft = 1000
            clearInterval(timer)
          }
          // 修改元素的位置
          box.style.left = nowLeft + 'px'
        }, 100)
      }
      // 清除定时器
      end.onclick = function () {
        clearInterval(timer)
      }
    </script>
  </body>
</html>
